<template>
  <div class="page-search">
    <BaseForm
      ref="baseForm"
      v-bind="searchFormConfig"
      :form-data="formData"
      :advanced="advanced"
      :default-items-num="defaultItemsNum"
      @updateFormData="updateFormData"
      v-on="$listeners"
    >
      <template #btns>
        <div class="btns">
          <el-button size="medium" type="primary" @click="handleSearch(false)">
            查询
          </el-button>

          <el-button
            v-if="searchFormConfig.exportBtn"
            size="medium"
            type="primary"
            @click="handleExport"
          >
            导出
          </el-button>


          <el-button size="medium" @click="handleSearch(true)">
            重置
          </el-button>
          <el-button
            v-if="searchFormConfig.formItems.length > defaultItemsNum"
            type="text"
            style="margin-left: 8px"
            size="medium"
            class="advanced"
            @click="toggleAdvanced"
          >
            {{ advanced ? "收起" : "更多" }}
            <i :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" />
          </el-button>
        </div>
      </template>
    </BaseForm>
  </div>
</template>

<script>
import BaseForm from "@/base-ui/form";
export default {
  components: {
    BaseForm,
  },
  props: {
    searchFormConfig: {
      type: Object,
      required: true,
    },
    defaultItemsNum: {
      type: Number,
      default: 2,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      formOrginData: {},
      advanced: false,
    };
  },
  created() {
    const formItems = this.searchFormConfig.formItems ?? [];
    for (const item of formItems) {
      this.formOrginData[item.field] = item.value ?? "";
    }
    this.handleSearch(true);
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleExport() {
      this.$emit("exportBtnClick");
    },
    handleSearch(isInit) {
      if (isInit) {
        this.$emit("update:formData", { ...this.formOrginData });
      }
      this.$nextTick(() => {
        this.$refs.baseForm.$refs.elForm.clearValidate();
        this.$emit("searchBtnClick");
      });
    },
    updateFormData({ value, field }) {
      this.formData[field] = value;
    },
  },
};
</script>

<style lang="scss" scoped>
.page-search {
  padding-top: 16px;
  background: #fff;
  margin-top: 16px;
}
.btns {
  margin-bottom: 20px;
  text-align: right;
  flex: 1;
}
</style>
